<!-- eslint-disable brace-style -->
<!-- eslint-disable vue/valid-v-for -->
<template>
  <!-- 实时分析 -->

  <!-- 实体行为部分 -->
  <div class="rule-label">
    <!-- 头部信息 -->
    <div class="small-head">
      <div>
        <el-button
          type="primary"
          :icon="showAction ? 'el-icon-minus' : 'el-icon-plus'"
          class="small-head-btn"
          @click="showAction = !showAction"
        />实体行为
      </div>
    </div>
    <!-- 内容区域 -->
    <el-form v-show="showAction" class="floor3" @submit.native.prevent>
      <div v-for="(item, index) in formData.action.conditions" :key="index" style="margin-bottom: 30px">
        <!-- 第一行 -->
        <div class="happend">
          <!-- 字母 -->
          <div class="number-tips">{{ letters[index] }}</div>

          <el-form-item prop="item.arrSel">
            <el-select v-model="item.done" filterable placeholder="请选择" style="margin: 0 15px; width: 100px">
              <el-option label="做过" :value="true" />
              <el-option label="未做过" :value="false" disabled />
            </el-select>
          </el-form-item>
          <el-form-item :prop="item.event">
            <!--            <el-select-->
            <!--              v-model="item.event"-->
            <!--              filterable-->
            <!--              placeholder="请选择"-->
            <!--              style="margin-right: 15px; width: 230px"-->
            <!--              @change="(val) => resetList(val, index)"-->
            <!--            >-->
            <!--              <el-option-->
            <!--                v-for="i in formData.transferArray.actionList"-->
            <!--                :key="i.value"-->
            <!--                :label="i.label"-->
            <!--                :value="i.value"-->
            <!--              />-->
            <!--            </el-select>-->
            <el-cascader
              v-model="item.event"
              :options="formData.transferArray.actionList"
              :props="{ expandTrigger: 'hover',emitPath:false }"
              @change="(val) => resetList(val, index)"
            />
          </el-form-item>

          <el-button type="text" @click="addSel(index)">+添加筛选 </el-button>
          <i v-if="index > 0" class="el-icon-close" style="margin-left: 10px" @click="removeHappend(index)" />
        </div>
        <!-- 第二行满足条件部分 -->
        <div v-if="item.conditions.length > 0" class="stepConditions">
          <div class="satisfid-section">
            <div class="satisfid-line">并且满足</div>
            <div class="show-cus-line" />
            <div v-if="item.conditions.length > 1" class="line-components">
              <div class="divider" />
              <el-button class="changeBtn" @click="changeLogic(item)">{{
                item.relation === 'and' ? '且' : '或'
              }}</el-button>
              <div class="divider" />
            </div>
            <ul class="ul-list">
              <li v-for="(it, idx) in item.conditions" :key="it + idx + 'll'">
                <el-select
                  v-model="it.field"
                  filterable
                  placeholder="请选择"
                  style="margin-right: 15px; width: 230px"
                  @change="
                    (val) => {
                      confirmActFirst(val, index, idx)
                    }
                  "
                >
                  <el-option
                    v-for="i in formData.transferArray.actionFirstList[index].list"
                    :label="i.label"
                    :value="i.value"
                  />
                </el-select>
                <el-select
                  v-model="it.operator"
                  filterable
                  placeholder="请选择"
                  style="margin-right: 15px; width: 230px"
                  @change="
                    (val) => {
                      confirmActSec(val, index, idx,it)
                    }
                  "
                >
                  <el-option
                    v-for="i in formData.transferArray.actionSecondList[index].lists[idx].list"
                    :label="i.label"
                    :value="i.value"
                  />
                </el-select>
                <el-select
                  v-if="it.operator!='ref_in' && it.operator!='ref_not_in' && it.useType!='input'"
                  v-model="it.param"
                  filterable
                  :multiple="it.useType != 'normal'"
                  style="width: 300px"
                  clearable
                  @change="handleChangeInput"
                >
                  <el-option
                    v-for="i in formData.transferArray.actionEnumList[index].lists[idx].list"
                    :label="i.label"
                    :value="i.value"
                  />
                </el-select>
                <!-- 新加基线判断  -->
                <!-- <el-select
                  v-else-if=""
                  v-model="it.param"
                  filterable
                  :multiple="false"
                  style="width: 300px"
                  clearable
                  @change="handleChangeInput"
                >
                  <el-option
                    v-for="i in formData.transferArray.actionEnumList[index].lists[idx].list"
                    :label="i.label"
                    :value="i.value"
                  />
                </el-select> -->

                <!-- 相等或者正则      -->
                <el-input v-else-if="it.useType == 'input'" v-model="it.param" style="width: 300px" @input="handleChangeInput" />
                <!-- 包含或者不包含 -->

                <MultipInput
                  v-else-if="it.useType === 'a-select'"
                  :tags="it.param"
                  style="width: 300px"
                  @emitInput="(val) => emitActionInput(val, index, idx)"
                />

                <!-- 时间选择器 -->

                <div v-else-if="it.useType === 'datetime'" style="display: inline-block">
                  <el-time-picker
                    v-model="it.tempParam1"
                    style="width: 150px"
                    value-format="HH:mm:ss"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    placeholder="选择时间范围"
                  />
                  至
                  <el-time-picker
                    v-model="it.tempParam2"
                    style="width: 150px"
                    value-format="HH:mm:ss"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    placeholder="选择时间范围"
                  />
                </div>
                <!-- 关联资源表 -->
                <el-select v-else v-model="it.refResource" filterable style="width: 300px" @change="$forceUpdate()">
                  <el-option v-for="i in formData.transferArray.resourceList" :label="i.label" :value="i.value" />
                </el-select>

                <i class="el-icon-close" style="margin-left: 10px" @click="removeConditon(index, idx)" />
              </li>
            </ul>
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import { changeAction } from '@/views/icp/rule/utils/rule'
import MultipInput from './multipInput.vue'
export default {
  components: { MultipInput },
  props: {
    form: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      // 表单数据
      // 行为下拉选择
      typeOptions: [
        { label: '实时', value: '实时' },
        { label: '2', value: '2' }
      ],
      //   是否展示实体属性
      showAttr: true,
      // 是否展示实体行为
      showAction: true
    }
  },
  computed: {
    formData() {
      return this.form
    },
    letters() {
      const arr = []
      for (var i = 0; i < 26; i++) {
        arr.push(String.fromCharCode(65 + i))
      }
      return arr
    }
  },

  mounted() {
    if (this.formData.action.conditions.length === 0) {
      this.formData.action.conditions = [
        {
          alias: 'A',
          done: true,
          event: '',
          relation: 'and',
          conditions: [
            {
              field: '',
              operator: '',
              param: undefined,
              type: '',
              useType: ''
            }
          ]
        }
      ]
      this.formData.transferArray.actionFirstList.push({ list: [] })
      this.formData.transferArray.actionSecondList.push({
        lists: [{ list: [] }]
      })
      this.formData.transferArray.actionEnumList.push({
        lists: [{ list: [] }]
      })
    }
    this.exportObj()
  },
  methods: {
    handleChangeInput() {
      this.$forceUpdate()
    },
    // 处理行为第一步数据
    formatting(val, arr, it, typevalue, index, idx) {
      if (val) {
        const types = arr.filter((i) => {
          return i.value === val
        })
        it.isEnum = types[0].isEnum
        it.valueType = types[0].type
        it.type = typevalue
        // 判断是否可枚举
        if (it.isEnum === 0) {
          this.formData.transferArray.actionSecondList[index].lists[idx].list =
            this.formData.transferArray.typeOptions.filter((ii) => {
              return ii.type === it.valueType  ||  ii.value.includes('baseline')
             
            })
        } else {
          this.formData.transferArray.actionSecondList[index].lists[idx].list =
            this.formData.transferArray.typeOptions.filter((ii) => {
              return ii.type === 'json' || ii.value.includes('baseline')
            })
          it.useType = 'enum'
          // 获取第三个列表值
          this.formData.transferArray.actionEnumList[index].lists[idx].list = types[0].enumList.map((s) => {
            return {
              value: s.dictValue,
              label: s.dictKey,
              propId: s.groupId,
              id: s.id,
              type: s.type
            }
          })
        }
      }
    },
    // 处理第二步数据
    formatActSec(val, it, typevalue,index,idx) {
      if (it.isEnum === 0) {
        if (val === 'equal' || val === 'regex' || val === 'len_gt') {
          it.useType = 'input'
        } else if (val === 'in' || val === 'not_in') {
          it.useType = 'a-select'
          it.param = []
        } else if (val === 'in_time_range') {
          it.useType = 'datetime'
        } else {
          it.useType = 'outer'
        }
      } else {
        if (val === 'equal') {
          it.useType = 'normal'
        }else {
          it.useType = ''
        }
      }
       if(val.includes('baseline')){
          it.useType = 'normal'
          this.formData.transferArray.actionEnumList[index].lists[idx].list=this.formData.transferArray.baselines
        }
    },
    // 修改实体事件
    async resetList(val, index) {
      await changeAction(val, index, this.formData.transferArray)
      this.formData.action.conditions[index].conditions.forEach((item) => {
        item.field = ''
        item.operator = ''
        item.param = undefined
        item.refResource = ''
      })
      this.exportObj()
    },
    // 修改实体行为组第一项值
    confirmActFirst(val, index, idx) {
      const it = this.formData.action.conditions[index].conditions[idx]
      this.formatting(val, this.formData.transferArray.actionFirstList[index].list, it, 'filter', index, idx)
      it.operator = ''
      it.param = undefined
      it.refResource = ''
    },
    // 修改实体行为组第2项值
    confirmActSec(val,index,idx) {
      const it = this.formData.action.conditions[index].conditions[idx]
      this.formatActSec(val, it, 'filter',index,idx)

      if (val === 'in' || val === 'not_in') {
        it.param = []
      } else {
        it.param = ''
      }
      it.refResource = ''
    },

    // 行为多选组件返回的值
    emitActionInput(val, index, idx) {
      this.formData.action.conditions[index].conditions[idx].param = val
    },

    //   更改判断逻辑
    changeLogic(item) {
      item.relation = item.relation === 'and' ? 'or' : 'and'
    },
    // 测试实体行为并且部分是否填全
    testAction(item) {
      return item.every(it => {
        return it.field && it.operator && (it.param?.toString().length || it.refResource || (it.tempParam1 && it.tempParam2))
      })
    },
    //   添加条件
    addSel(index) {
      const isFilled = this.testAction(this.formData.action.conditions[index].conditions)
      if (!isFilled) {
        this.$message.warning('实体行为含有空白项未填全')
        return
      }
      this.formData.action.conditions[index].conditions.push({
        field: '',
        operator: '',
        param: '',
        refResource: '',
        params: []
      })
      this.formData.transferArray.actionSecondList[index].lists.push({
        list: []
      })
      this.formData.transferArray.actionEnumList[index].lists.push({
        list: []
      })
    },
    //   删除组
    removeHappend(index) {
      this.formData.action.conditions.splice(index, 1)
    },
    // 移除满足条件
    removeConditon(index, idx) {
      this.formData.action.conditions[index].conditions.splice(idx, 1)
      this.formData.transferArray.actionSecondList[index].lists.splice(idx, 1)
      this.formData.transferArray.actionEnumList[index].lists.splice(idx, 1)
    },
    // 保存表单
    submitLabel() {
      const isFilled = this.formData.action.conditions.every(item => {
        const actionFilled = this.testAction(item.conditions)
        const { event } = item
        return actionFilled && event
      })
      if (!isFilled) {
        this.$message.warning('请补全实体行为组')
        return
      }
      this.formData.refResource = []
      this.formData.action.conditions.forEach((item, index) => {
        // 整理params格式
        if (item.param || item.param === 0) {
          if (Array.isArray(item.param)) {
            item.params = item.param
          } else {
            // 非数组格式
            item.params = [item.param]
          }
        }
        // 整合资源列表
        if (item.refResource) {
          this.formData.refResource.push(item.refResource)
        }
        item.conditions.forEach((it) => {
          if (it.refResource) {
            this.formData.refResource.push(it.refResource)
            it.params = [it.refResource]
          } else if (it.tempParam1 && it.tempParam2) {
            it.params = [it.tempParam1 + '-' + it.tempParam2]
            // eslint-disable-next-line brace-style
          }
          // 数组格式
          else {
            if (Array.isArray(it.param)) {
              it.params = it.param
            } else {
              // 非数组格式
              it.params = [it.param]
            }
          }
        })
      })
      this.formData.refResource = Array.from(new Set(this.formData.refResource))
      const rule = {
        rule: this.formData
      }
      return new Promise((resolve, reject) => {
        resolve(rule)
      })
    },
    // 修改传递给desc的值
    exportObj() {
      const obj = {
        behavior_field_data: []
      }
      // 所有的子项目集合

      this.formData.transferArray.attrList.forEach((item) => {
        obj.behavior_field_data.push(`#{${item.label}}`)
      })

      if (this.formData.action.conditions.length > 0) {
        this.formData.action.conditions.forEach((item, index) => {
          this.formData.transferArray.actionFirstList[0].list.forEach((i, idx) => {
            obj.behavior_field_data.push(`#{${this.letters[index]}.${i.name}}`)
            if (JSON.stringify(obj.behavior_field_data).search(`${this.letters[index]}.分析时间段}`) === -1) {
              obj.behavior_field_data.push(`#{${this.letters[index]}.分析时间段}`)
            }
            if (JSON.stringify(obj.behavior_field_data).search(`${this.letters[index]}.聚合值}`) === -1) {
              obj.behavior_field_data.push(`#{${this.letters[index]}.聚合值}`)
            }
          })
        })
      }

      this.$emit('exportObj', obj)
    }
  }
}
</script>

<style lang="scss" scoped>
.line-components {
  display: flex;
  flex-direction: column;
  width: 24px;
  .divider {
    margin: 0 auto;
    height: calc(50% - 12px);
    width: 1px;
    background-color: #cfe4fe;
  }
  .changeBtn {
    width: 24px;
    height: 24px;
    text-align: center;
    padding: 0;
    background-color: #cfe4fe;
    color: #2979ff;
  }
}

.rule-label {
  border: 1px solid #e2e2e2;
  padding: 20px;

  width: calc(100% - 20px);

  section {
    display: flex;
    margin: 20px 0;
    align-items: center;
  }
  .small-head {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    .small-head-btn {
      text-align: center;
      border-radius: 2px;
      padding: 0;
      border: 1px solid #95989c;
      align-content: center;
      margin-right: 10px;
    }
  }

  .floor3 {
    padding-left: 0px;
    .happend {
      display: flex;
      align-items: center;
      .floor3_son {
        margin-right: 8px;
        line-height: 32px;
        text-align: center;
      }
      .number-tips {
        width: 24px;
        height: 24px;
        line-height: 20px;
        border-radius: 2px;
        padding: 3px 7px;
        background: #2979ff;
        color: #fff;
        margin-right: 10px;
        text-align: center;
      }
      //   & > * {
      //     margin-bottom: 20px;
      //   }
    }
    .stepConditions {
      margin: 20px 0;
      // padding-left: 30px;
      width: 100%;
      .satisfid-section {
        display: flex;
        .satisfid-line {
          width: 65px;
          display: flex;
          align-items: center;
          color: #95989c;
          margin-right: 10px;
        }
        .show-cus-line {
          width: 2px;
          background-color: #2979ff;
          margin-right: 12px;
        }

        .ul-list {
          width: 100%;
          padding-left: 10px;
          margin: 0;
          & > li {
            list-style: none;
            text-align: left;
            margin-bottom: 10px;
          }
        }
      }
    }
  }

  .info {
    padding: 0 5px;
    height: 32px;
    background: #f0f0f0;
    border-radius: 2px;
    color: #95989c;
  }
  .arrsel {
    display: flex;
    align-items: center;
  }
  .no-pointer {
    cursor: not-allowed;
  }
}
</style>
